﻿/*
 * Copyright (c) 2012, Will Strohl
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, this 
 * list of conditions and the following disclaimer.
 * 
 * * Redistributions in binary form must reproduce the above copyright notice, this 
 * list of conditions and the following disclaimer in the documentation and/or other 
 * materials provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
 * POSSIBILITY OF SUCH DAMAGE.
 * 
*/

using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using System;
using DotNetNuke.Services.Localization;
using System.Text.RegularExpressions;
using WillStrohl.Modules.BookmarkCollector.Components;

namespace WillStrohl.Modules.BookmarkCollector
{
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The EditBookmarkCollector class is used to manage content
    /// 
    /// Typically your edit control would be used to create new content, or edit existing content within your module.
    /// The ControlKey for this control is "Edit", and is defined in the manifest (.dnn) file.
    /// 
    /// Because the control inherits from BookmarkCollectorModuleBase you have access to any custom properties
    /// defined there, as well as properties from DNN such as PortalId, ModuleId, TabId, UserId and many more.
    /// 
    /// </summary>
    /// -----------------------------------------------------------------------------
    public partial class Edit : BookmarkCollectorModuleBase
    {

        #region Private Members

        private int bookmarkId = Null.NullInteger;

        #endregion

        #region Properties

        protected int BookmarkId
        {
            get
            {
                if (bookmarkId != Null.NullInteger) return bookmarkId;

                if (Request.QueryString["BookmarkId"] != null)
                {
                    bookmarkId = int.Parse(Request.QueryString["BookmarkId"]);
                }

                return bookmarkId;
            }
        }

        protected bool IsBookmarkValid
        {
            get { return (BookmarkId != Null.NullInteger); }
        }

        #endregion

        #region  Event Handlers

        /// <summary>
        /// OnInit - initialization of the module
        /// </summary>
        /// <param name="e"></param>
        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(Page_Load);
            cmdSave.Click += new System.EventHandler(cmdSave_Click);
            cmdReturn.Click += new System.EventHandler(cmdReturn_Click);
            cmdDelete.Click += new System.EventHandler(cmdDelete_Click);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack) BindData();
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void cmdSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid) SaveBookmark();
        }

        protected void cmdReturn_Click(object sender, EventArgs e)
        {
            SendBackToModule();
        }

        protected void cmdDelete_Click(object sender, EventArgs e)
        {
            DeleteBookmark();
        }

        #endregion

        #region Databinding

        private void BindData()
        {
            LocalizeModule();

            cmdDelete.Visible = IsBookmarkValid;

            // check to see if there is a bookmark available (passed through the URL)
            if (IsBookmarkValid)
            {
                var ctlModule = new BookmarkController();

                // get the bookmark data 
                var bookmark = ctlModule.GetContentItem(BookmarkId);

                // load the form fields
                if (bookmark != null)
                {
                    txtTitle.Text = bookmark.Title;
                    txtUrl.Text = bookmark.Url;
                }
                else
                {
                    throw new ArgumentOutOfRangeException("The BookmarkID provided does not match a valid bookmark record.");
                }
            }
        }

        private void LocalizeModule()
        {
            rfvTitle.ErrorMessage = Localization.GetString("rfvTitle.ErrorMessage", LocalResourceFile);
            rfvUrl.ErrorMessage = Localization.GetString("rfvUrl.ErrorMessage", LocalResourceFile);
            revUrl.ErrorMessage = Localization.GetString("revUrl.ErrorMessage", LocalResourceFile);
            cmdReturn.Text = Localization.GetString("cmdCancel.Text", Localization.SharedResourceFile);
            cmdDelete.Text = Localization.GetString("cmdDelete.Text", Localization.SharedResourceFile);
            cmdSave.Text = Localization.GetString("cmdUpdate.Text", Localization.SharedResourceFile);
        }

        #endregion

        #region Data Events

        private void SaveBookmark()
        {
            var sec = new PortalSecurity();
            var ctlModule = new BookmarkController();
            var bookmark = new BookmarkInfo();

            bookmark.Title = CleanInput(ref sec, txtTitle.Text);
            bookmark.Url = CleanInput(ref sec, txtUrl.Text);

            if (IsBookmarkValid)
            {
                ctlModule.UpdateContentItem(TabId, ModuleId, BookmarkId, bookmark);
            }
            else
            {
                ctlModule.CreateContentItem(TabId, ModuleId, bookmark);
            }

            // return to the module view
            SendBackToModule();
        }

        private void DeleteBookmark()
        {
            var ctlModule = new BookmarkController();
            ctlModule.DeleteContentItem(BookmarkId);

            SendBackToModule();
        }

        #endregion

        #region Helper Methods

        private void SendBackToModule()
        {
            Response.Redirect(Globals.NavigateURL());
        }

        private string CleanInput(ref PortalSecurity security, string input)
        {
            input = input.Trim();
            input = Regex.Replace(input, @"\|", string.Empty);
            input = security.InputFilter(input, PortalSecurity.FilterFlag.NoMarkup);

            return input;
        }

        #endregion

    }
}